package com.yuyu.sequence.seq;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 序列生产者
 *
 * @author yuyu
 * @date 2018/12/5
 */
public class SeqProducer {

    /**
     * 序列键值对
     */
    private static Map<Integer, BlockingQueue<Long>> map = new HashMap<>();

    private SeqProducer() {
        init();
    }

    /**
     * 单例模式
     */
    private static class SingletonHolder {

        private static SeqProducer INSTANCE = new SeqProducer();
    }

    /**
     * 获取实例
     */
    public static SeqProducer getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 序列初始化
     */
    private void init() {
        for (SeqConstant.SeqEnum seq : SeqConstant.SeqEnum.values()) {
            BlockingQueue<Long> queue = new ArrayBlockingQueue<Long>(seq.getClientQueueSize());
            map.put(seq.getId(), queue);
            SeqEntity seqEntity = new SeqEntity(seq, queue);
            SeqTask seqTask = new SeqTask(seqEntity);
            seqTask.start();

        }

    }

    /**
     * 获取序列
     *
     * @param id 序列号
     */
    public static Long getSeq(int id) {
        BlockingQueue<Long> queue = map.get(id);
        Long seq = null;
        try {
            seq = queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return seq;
    }
}
